package com.qingyun.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.config.QingYunConfig;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.mybatisplus.core.ServicePlusImpl;
import com.qingyun.common.core.page.PagePlus;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.exception.CustomException;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.common.utils.mp3.Mp3Info;
import com.qingyun.common.utils.mp3.Mp3Utils;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokBgm;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.TiktokTag;
import com.qingyun.shop.domain.TiktokTagToBgm;
import com.qingyun.shop.domain.bo.bgm.TiktokBgmAddBo;
import com.qingyun.shop.domain.bo.bgm.TiktokBgmEditBo;
import com.qingyun.shop.domain.bo.bgm.TiktokBgmQueryBo;
import com.qingyun.shop.domain.vo.TiktokBgmDetailVo;
import com.qingyun.shop.domain.vo.TiktokBgmVo;
import com.qingyun.shop.domain.vo.TiktokTagSelectListVo;
import com.qingyun.shop.mapper.TiktokBgmMapper;
import com.qingyun.shop.mapper.TiktokTagMapper;
import com.qingyun.shop.mapper.TiktokTagToBgmMapper;
import com.qingyun.shop.service.ITiktokBgmService;
import com.qingyun.shop.service.ITiktokShopService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * bgm资源Service业务层处理
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Service
@AllArgsConstructor
public class TiktokBgmServiceImpl extends ServicePlusImpl<TiktokBgmMapper, TiktokBgm, TiktokBgmVo> implements ITiktokBgmService {

    private final TiktokTagToBgmMapper tagToBgmMapper;

    private final MapperFacade mapperFacade;

    private final TiktokTagMapper tagMapper;

    private final ITiktokShopService shopService;

    @Override
    public TiktokBgmDetailVo queryById(Long id) {
        TiktokBgm tiktokBgm = baseMapper.selectById(id);
        TiktokBgmDetailVo vo = mapperFacade.map(tiktokBgm, TiktokBgmDetailVo.class);

        List<TiktokTagToBgm> tiktokTagToBgms = tagToBgmMapper.selectList(Wrappers.query(new TiktokTagToBgm().setBgmId(vo.getId())));

        if (tiktokTagToBgms != null && tiktokTagToBgms.size() > 0) {
            List<Long> tagIds = tiktokTagToBgms.stream().map(TiktokTagToBgm::getTagId).collect(Collectors.toList());
            List<Long> tags = tagMapper.selectBatchIds(tagIds).stream().map(TiktokTag::getTId).collect(Collectors.toList());
            vo.setTags(tags);
        }

        return vo;
    }

    @Override
    public TableDataInfo<TiktokBgmVo> queryPageList(TiktokBgmQueryBo bo) {

        PagePlus<TiktokBgm, TiktokBgmVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
        result.getRecordsVo().forEach(r -> {
            r.setDurationStr(DateUtil.secondToTime(r.getDuration().intValue()));
            List<TiktokTagToBgm> tiktokTagToBgms = tagToBgmMapper.selectList(Wrappers.query(new TiktokTagToBgm().setBgmId(r.getId())));
            if (tiktokTagToBgms != null && tiktokTagToBgms.size() > 0) {
                List<Long> tagIds = tiktokTagToBgms.stream().map(TiktokTagToBgm::getTagId).collect(Collectors.toList());
                List<TiktokTag> tiktokTags = tagMapper.selectBatchIds(tagIds);

                List<TiktokTagSelectListVo> tagNames = new ArrayList<>();

                tiktokTags.forEach(t -> {
                    TiktokTagSelectListVo select = new TiktokTagSelectListVo();
                    select.setLabel(t.getTagName());
                    select.setValue(t.getTId());
                    tagNames.add(select);
                });

                r.setTags(tagNames);
            }
            Map<String, Object> audio = new HashMap<>();
            audio.put("title",r.getTitle());
            audio.put("src", r.getAudioUrl());
            audio.put("pic", "https://source.qingyunclouds.com/resource/20210929/ae40da8ddfcb4916adaa7bc5b4a38a79.png");
            r.setAudio(audio);
            if(r.getShopId().equals(0L)){
				r.setShopName("平台");
			}else {
				TiktokShop one = shopService.lambdaQuery().select(TiktokShop::getName).eq(TiktokShop::getId, r.getShopId()).one();
				r.setShopName(one.getName());

			}

		});


        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<TiktokBgmVo> queryList(TiktokBgmQueryBo bo) {
        return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<TiktokBgm> buildQueryWrapper(TiktokBgmQueryBo bo) {
        LambdaQueryWrapper<TiktokBgm> lqw = Wrappers.lambdaQuery();

        lqw.eq(bo.getStatus() != null, TiktokBgm::getStatus, bo.getStatus());
        lqw.eq(bo.getGlobal() != null, TiktokBgm::getGlobal, bo.getGlobal());

        if (!SecurityUtils.isManager()) {
            Long shopId = SecurityUtils.getShop().getId();
            lqw.eq(TiktokBgm::getShopId, shopId);
        }
        lqw.orderByDesc(TiktokBgm::getCreateTime);

        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(TiktokBgmAddBo bo) {
        TiktokBgm add = BeanUtil.toBean(bo, TiktokBgm.class);
        if (!SecurityUtils.isManager()) {
            add.setShopId(SecurityUtils.getShop().getId());
			bo.setGlobal(1);
        } else {
            //管理员是全局bgm
            bo.setGlobal(0);
        }
        add.setCreateBy(SecurityUtils.getUsername());
        add.setCreateTime(new Date());
        add.setUpdateBy(SecurityUtils.getUsername());
        add.setUpdateTime(new Date());
        Mp3Info mp3Info;
        try {
            mp3Info = Mp3Utils.instance(add.getAudioUrl());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("音乐文件解析出错");
        }
        add.setDuration(mp3Info.getDuration());
        save(add);

        // 添加bgm与标签关联
		if(SecurityUtils.isManager()){
			bo.getTags().forEach(t -> {
				tagToBgmMapper.insert(new TiktokTagToBgm().setTagId(t).setBgmId(add.getId()).setShopId(0L));
			});
		}else{
			bo.getTags().forEach(t -> {
				tagToBgmMapper.insert(new TiktokTagToBgm().setTagId(t).setBgmId(add.getId()).setShopId(SecurityUtils.getShop().getId()));
			});
		}


        return Boolean.TRUE;
    }

    @Override
    public Boolean updateByBo(TiktokBgmEditBo bo) {
        TiktokBgm update = BeanUtil.toBean(bo, TiktokBgm.class);
        // 删除bgm与tag的关联
        tagToBgmMapper.delete(Wrappers.query(new TiktokTagToBgm().setBgmId(bo.getId())));
		// 添加bgm与标签关联
		if(SecurityUtils.isManager()){
			bo.getTags().forEach(t -> {
				tagToBgmMapper.insert(new TiktokTagToBgm().setTagId(t).setBgmId(bo.getId()).setShopId(0L));
			});
		}else{
			bo.getTags().forEach(t -> {
				tagToBgmMapper.insert(new TiktokTagToBgm().setTagId(t).setBgmId(bo.getId()).setShopId(SecurityUtils.getShop().getId()));
			});
		}
        return updateById(update);
    }

	@Override
	public TiktokBgm selectBgmBy(Long shopId, Long activityId, Double duration,Boolean size) {
		return baseMapper.selectBgmBy(shopId,activityId, duration,size);
	}

	@Override
	public TiktokBgm selectRandomBgm(Long shopId, Integer global, Double totalDuration, boolean size) {
		return baseMapper.selectRandomBgm(shopId,global,totalDuration,size);
	}

	@Transactional
	@Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		List<TiktokBgm> tiktokBgms = listByIds(ids);
		tiktokBgms.forEach(b -> {
			String localPath = QingYunConfig.getProfile() + StringUtils.substringAfter(b.getAudioUrl(),  Constants.RESOURCE_PREFIX);
			File file = new File(localPath);
			if (file.exists()) {
				file.delete();
			}
			tagToBgmMapper.delete(Wrappers.query(new TiktokTagToBgm().setBgmId(b.getId())));
        });
        return removeByIds(ids);
    }
}
